package com.lcc.lynx.jdbc.handle;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.BIGINT)
@MappedTypes({String.class, Long.class})
public class String2LongTypeHandler extends BaseTypeHandler<Serializable> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Serializable parameter, JdbcType jdbcType) throws SQLException {
        if (JdbcType.BIGINT == jdbcType) {
            if (parameter instanceof String) {
                ps.setLong(i, Long.parseLong((String) parameter));
            } else if (parameter instanceof Long) {
                ps.setLong(i, (Long) parameter);
            } else {
                ps.setLong(i, Long.parseLong(parameter.toString()));
            }
        }
    }

    @Override
    public Long getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return value != null ? Long.parseLong(value) : null;
    }

    @Override
    public Long getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return value != null ? Long.parseLong(value) : null;
    }

    @Override
    public Long getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return value != null ? Long.parseLong(value) : null;
    }
}
